package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Elasticsearch;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink08_SQL_Demo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
//                .socketTextStream("localhost", 9999)
                .readTextFile("input/sensor.csv")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.parseLong(line[1]), Integer.parseInt(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO - SQL

        // 创建表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 方式一： 先将 流 转成 Table对象，再将 表对象 注册为 临时视图，起一个名字
//        Table sensorTable = tableEnv.fromDataStream(sensorDS);
//        tableEnv.createTemporaryView("sensorTable", sensorTable);

        // TODO 方式二：一步到位：直接 将流转换成 Table，并且给一个名字，后续还可以获取 Table对象
        tableEnv.createTemporaryView("sensorTable", sensorDS);
        // 这种情况下，可以从 表名 获取出  table对象
        Table sensorTable1 = tableEnv.from("sensorTable");

        // 使用 SQL 进行操作
//        Table resultTable = tableEnv.sqlQuery("select * from " + sensorTable);    // 使用未注册表名的方式
        Table resultTable = tableEnv.sqlQuery("select * from sensorTable where id = 'sensor_1'");   // 使用注册的表名


        tableEnv.toAppendStream(resultTable, Row.class).print();


        env.execute();
    }
}


